<?php
/**
 * Created by PhpStorm.
 * User: PX780
 * Date: 2016/11/3
 * Time: 11:41
 */
require_once(LIB_PATH."view/header.inc.php");
require_once(ROOT_PATH."model/templower.model.php");
$modelObj->load();
$modelObj->find();
$allFields = $modelObj->field();
?>
<link href="js/editor/themes/default/css/umeditor.css" type="text/css" rel="stylesheet">
<!-- js 日期选择 -->
<script type="text/javascript" charset="utf-8" src="js/layDate-v5.0.9/laydate/laydate.js"></script>

<?php
if($modelObj->htmlField()) {
?>
<!-- html 编辑器 -->
<script>
           window.UEDITOR_HOME_URL = '/';

</script>
	<script type="text/javascript" charset="utf-8" src="js/editor/umeditor.config.js"></script>
	<script type="text/javascript" charset="utf-8" src="js/editor/umeditor.min.js"> </script>
	<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
	<script type="text/javascript" charset="utf-8" src="js/editor/lang/zh-cn/zh-cn.js"></script>
<?php
}
?>

	<!-- 引入插件 -->
	<script src="js/uploadimg.js?v=5" charset="utf-8"></script>
	<script>
		var ShowUploadImg = function(sourceId){
			var url = getFileUrl(sourceId);
			document.getElementById("imgPath").value = url;
			$("#imgPath").attr("data-image",url);
		}
	</script>
	<div class="panel admin-panel margin-top" id="add">
		<div class="panel-head"><strong><span class="icon-pencil-square-o"></span> 编辑内容</strong></div>
		<div class="body-content">
			<form method="post" id="upload" class="form-x" action="/templower,save,<?php echo $modelObj->key(); ?>,<?php echo $modelObj->keyVal();?>"  enctype="multipart/form-data" >
tempEdit


				<div class="form-group">
					<div class="label">
						<label> </label>
					</div>
					<div class="field">
						<button class="button bg-main icon-check-square-o" type="button" id="saveBtn" onclick="submitForm()"> 提交</button>
						<div class="tips"></div>
					</div>
				</div>
			<input type="hidden" name="pageNum" value="<?php echo r_int('pageNum');?>">
			</form>
		</div>
	</div>
<?php
if($modelObj->htmlField()){
?>
	<script type="text/javascript">
		//实例化编辑器
		var um = UM.getEditor('myEditor');
    um.addListener('blur',function(){
        $('#focush2').html('编辑器失去焦点了')
    });
    um.addListener('focus',function(){
        $('#focush2').html('')
    });
    //按钮的操作
    function insertHtml() {
        var value = prompt('插入html代码', '');
        um.execCommand('insertHtml', value)
    }
    function isFocus(){
        alert(um.isFocus())
    }
    function doBlur(){
        um.blur()
    }
    function createEditor() {
        enableBtn();
        um = UM.getEditor('myEditor');
    }
    function getAllHtml() {
        alert(UM.getEditor('myEditor').getAllHtml())
    }
    function getContent() {
        var arr = [];
        arr.push("使用editor.getContent()方法可以获得编辑器的内容");
        arr.push("内容为：");
        arr.push(UM.getEditor('myEditor').getContent());
        alert(arr.join("\n"));
    }
    function getPlainTxt() {
        var arr = [];
        arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容");
        arr.push("内容为：");
        arr.push(UM.getEditor('myEditor').getPlainTxt());
        alert(arr.join('\n'))
    }
    function setContent(isAppendTo) {
        var arr = [];
        arr.push("使用editor.setContent('欢迎使用umeditor')方法可以设置编辑器的内容");
        UM.getEditor('myEditor').setContent('欢迎使用umeditor', isAppendTo);
        alert(arr.join("\n"));
    }
    function setDisabled() {
        UM.getEditor('myEditor').setDisabled('fullscreen');
        disableBtn("enable");
    }

    function setEnabled() {
        UM.getEditor('myEditor').setEnabled();
        enableBtn();
    }

    function getText() {
        //当你点击按钮时编辑区域已经失去了焦点，如果直接用getText将不会得到内容，所以要在选回来，然后取得内容
        var range = UM.getEditor('myEditor').selection.getRange();
        range.select();
        var txt = UM.getEditor('myEditor').selection.getText();
        alert(txt)
    }

    function getContentTxt() {
        var arr = [];
        arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容");
        arr.push("编辑器的纯文本内容为：");
        arr.push(UM.getEditor('myEditor').getContentTxt());
        alert(arr.join("\n"));
    }
    function hasContent() {
        var arr = [];
        arr.push("使用editor.hasContents()方法判断编辑器里是否有内容");
        arr.push("判断结果为：");
        arr.push(UM.getEditor('myEditor').hasContents());
        alert(arr.join("\n"));
    }
    function setFocus() {
        UM.getEditor('myEditor').focus();
    }
    function deleteEditor() {
        disableBtn();
        UM.getEditor('myEditor').destroy();
    }
    function disableBtn(str) {
        var div = document.getElementById('btns');
        var btns = domUtils.getElementsByTagName(div, "button");
        for (var i = 0, btn; btn = btns[i++];) {
            if (btn.id == str) {
                domUtils.removeAttributes(btn, ["disabled"]);
            } else {
                btn.setAttribute("disabled", "true");
            }
        }
    }
    function enableBtn() {
        var div = document.getElementById('btns');
        var btns = domUtils.getElementsByTagName(div, "button");
        for (var i = 0, btn; btn = btns[i++];) {
            domUtils.removeAttributes(btn, ["disabled"]);
        }
    }

	</script>
<?php
}
?>

<script>
		function submitForm(){
			window.onbeforeunload = null;
			var isOk = true;
//			$("#contentError").html('');
//			var content = $.trim(UM.getEditor('editor').getContent());
//			if(content==''){
//				$("#contentError").html("<span style='color:red'>正文内容呢，亲!</span>");
//				isOk = false;
//			}
<?php
	foreach($allFields as $f=>$info){
		echo "
		if(typeof {$f}Check === \"function\") {
				var r = {$f}Check($('#{$f}').val(),'{$info[0]}');
				if(!r) {
					isOk = false;
					return ;
				}
		}
		";

	}



	$htmlFields = $modelObj->htmlField();
	$f = $htmlFields[0];
	if($f){
		echo 'var content =UM.getEditor(\'editor\').getContent();';
		echo '$("#'.$f.'").val(content);';
	}
?>
			if(isOk)
			{
				$("#upload").submit();
			}
		}//end submitForm
</script>
<script>
	<?php if($modelObj->htmlField()){
    ?>
	var onlineData = '<?php
			if($f){
			    $modelObj->$f = preg_replace("/'/","\"",$modelObj->$f);
				echo preg_replace("/[\r\n]/","<br />",$modelObj->$f);
			}
		 ?>';
	var localData = "";

	function readFromLocal() {
		if (localData == "") {
			UM.getEditor('editor').setContent(onlineData, false);
		} else {
			UM.getEditor('editor').setContent(localData, false);
		}
	}


	function restoreOnline() {
		if (confirm("确认读取线上版本吗？可能会丢失本地修改的内容！")) {
			UM.getEditor('editor').setContent(onlineData, false);
		}
	}

	$(document).ready(function() {
		UM.getEditor('editor').ready(function () {
<?php
if($modelObj->keyVal()){
?>
            localData = UM.getEditor('editor').execCommand("getlocaldata");
            readFromLocal();
<?php
}
?>
		});
	});

<?php
}
//外键表查询
$allForeign = $modelObj->foreignField();

$fun = "";
$sel = "";
foreach($allForeign as $f=> $foreignTable){//begin main foreach
	$className = mymodel::getClassName($foreignTable);
	if($className){

	require_once(mymodel::getClassFile($foreignTable));

	$subObj = new $className;
	$orderBy = '';
	if($modelObj->$f){//找关联数据
		$orderBy = " ORDER BY `".$subObj->key()."`={$modelObj->$f} DESC, `".$subObj->key()."` DESC";
	}

	$subResult = $subObj->findAll('1=1',$orderBy);

	$options = "";
	define('MAX_OPTION_COUNT',1000);
	$count = 0;
	foreach($subResult as $tmpSub){
		$tmpObj = new $className();
		$tmpObj->find($tmpSub[$modelObj->key()]);
		if($count > MAX_OPTION_COUNT) {
			$options .= "<option value=\'\'>手动录入...</option>";
			break;
		}
		$tmpFields = $tmpObj->field();
		$tmpI = 0;
		$nameFiled = "";
		foreach($tmpFields as $nameFiled=>$tmpInfo){//获取第二个字段的名称
			if($tmpI > 0) break;
			$tmpI++;
		}
		//echo('$nameFiled='.$nameFiled.'----');
		$key = $tmpObj->key();
		if(trim($nameFiled)){
			 if($modelObj->$f == $tmpSub[$key]){
				$options .= "<option selected value=\'{$tmpSub[$key]}\'>{$tmpSub[$key]}({$tmpSub[$nameFiled]})</option>";
			}else{
				$options .= "<option value=\'{$tmpSub[$key]}\'>{$tmpSub[$key]}({$tmpSub[$nameFiled]})</option>";
			}
		}
		$count++;
	}//end sub foreach
	$fun .=  "function change{$f}(t){
		$('#{$f}').val(t);
		if(typeof {$f}Ex === \"function\") { //是函数其中 FunName 为函数名称,定义函数名为字段名加Ex，可以自动调用
				{$f}Ex(t);
		}
	}\r\n";
	$sel .= "$('#{$f}').after('<select class=\'mtop10\' onchange=\'change{$f}(this.options[this.options.selectedIndex].value)\' id=\'{$f}_helper\'><option value=\'{$defaultModelObj->$f}\'>请选择</option>{$options}</select>');\r\n";
	}//end if
}//end main foreach

$allStatus = $modelObj->statusField();
foreach($allStatus as $f=> $values){//begin main foreach
	$options = "";
	foreach($values as $v=> $info){
		if($modelObj->$f == $v){
			$options .= "<option selected value=\'{$v}\'>{$info[0]}({$v})</option>";
		}else{
			$options .= "<option  value=\'{$v}\'>{$info[0]}({$v})</option>";
		}
	}//end sub foreach
	$fun .=  "function change{$f}(t){
		$('#{$f}').val(t);
		if(typeof {$f}Ex === \"function\") { //是函数其中 FunName 为函数名称
				{$f}Ex(t);
		}
	}\r\n";
	$sel .= "$('#{$f}').after('<select class=\'mtop10\' onchange=\'change{$f}(this.options[this.options.selectedIndex].value)\' id=\'{$f}_helper\'><option value=\'{$defaultModelObj->$f}\'>请选择</option>{$options}</select>');\r\n";
}//end main foreach

echo $fun;
?>

$(document).ready(function(){
	<?php
	echo $sel;
	?>
});

window.onbeforeunload = function(event) {
	//return confirm("确定离开此页面吗？");
}
</script>
<?php
require_once(LIB_PATH."view/footer.inc.php");
?>